package com.sun.elasticjob.config;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.sun.elasticjob.job.FileBackupJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticJobConfig {

    @Value("${simpleJob.cron}")
    private String cron;
    @Value("${simpleJob.sharding-total-count}")
    private int shardingTotalCount;
    @Value("${simpleJob.sharding-item-parameters}")
    private String shardingItemParameters;
    @Value("${simpleJob.job-parameter}")
    private String jobParameter;
    @Value("${simpleJob.job-description}")
    private String jobDescription;
    @Value("${simpleJob.failover}")
    private Boolean failover;
    @Value("${simpleJob.misfire}")
    private Boolean misfire;

    @Autowired
    FileBackupJob fileBackupJob;
    @Autowired
    ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Autowired
    JobEventConfiguration jobEventConfiguration;
    @Autowired
    ElasticJobListener elasticJobListener;

    @Bean(initMethod = "init")
    public SpringJobScheduler initSimpleElasticJob() {
        return new SpringJobScheduler(fileBackupJob, zookeeperRegistryCenter,
                createJobConfiguration(), jobEventConfiguration, elasticJobListener);
    }

    private LiteJobConfiguration createJobConfiguration() {
        // 创建作业核心配置
        JobCoreConfiguration.Builder jobCoreConfigBuilder = JobCoreConfiguration.
                newBuilder(fileBackupJob.getClass().getName(), cron, shardingTotalCount);

        JobCoreConfiguration jobCoreConfig = jobCoreConfigBuilder
                .shardingItemParameters(shardingItemParameters)
                .jobParameter(jobParameter)
                .description(jobDescription)
                .failover(failover)
                .misfire(misfire)
                .build();

        // 创建Simple类型任务配置
        SimpleJobConfiguration simpleJobConfiguration =
                new SimpleJobConfiguration(jobCoreConfig, FileBackupJob.class.getCanonicalName());

        // 定义Lite作业配置
        LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration.
                newBuilder(simpleJobConfiguration)
                .monitorPort(9888)// dump端口
                .jobShardingStrategyClass("com.sun.elasticjob.strategy.MyShardingStrategy")// 作业分片策略实现类全路径
                .overwrite(true).build();
        return liteJobConfiguration;
    }

}
